<!-- 订阅页面 - 邮件订阅和RSS订阅源功能 -->
<template>
    <div class="subscribe-page">
        <!-- 统一导航栏组件 -->
        <AppHeader />

        <!-- 主要内容区域 -->
        <main class="main-content">
            <div class="content-wrapper">
                <!-- 页面标题区域 -->
                <div class="page-header">
                    <h1 class="page-title">订阅更新</h1>
                    <p class="page-description">
                        订阅我的博客，第一时间获取最新文章和技术分享
                    </p>
                </div>

                <!-- 示例数据提示 -->
                <div v-if="isUsingSampleData" class="sample-data-notice">
                    <el-alert
                        title="示例数据模式"
                        description="后端服务暂时不可用，当前使用示例数据进行演示。"
                        type="info"
                        :closable="false"
                        show-icon
                    />
                </div>

                <!-- 订阅功能区域 -->
                <div class="subscribe-content">
                    <!-- 邮件订阅区域 -->
                    <div class="subscribe-section">
                        <div class="section-header">
                            <div class="section-icon">
                                <el-icon>
                                    <Message />
                                </el-icon>
                            </div>
                            <h2 class="section-title">邮件订阅</h2>
                            <p class="section-description">
                                订阅邮件通知，新文章发布时第一时间收到通知
                            </p>
                        </div>

                        <!-- 邮件订阅表单 -->
                        <div class="subscribe-form">
                            <el-form ref="emailFormRef" :model="emailForm" :rules="emailRules" label-width="0"
                                @submit.prevent="handleEmailSubscribe">
                                <div class="form-row">
                                    <el-form-item prop="email" class="email-input">
                                        <el-input v-model="emailForm.email" placeholder="请输入您的邮箱地址" size="large"
                                            :disabled="emailSubscribing">
                                            <template #prefix>
                                                <el-icon>
                                                    <Message />
                                                </el-icon>
                                            </template>
                                        </el-input>
                                    </el-form-item>
                                    <el-button type="primary" size="large" :loading="emailSubscribing"
                                        @click="handleEmailSubscribe" class="subscribe-btn">
                                        {{ emailSubscribing ? '订阅中...' : '立即订阅' }}
                                    </el-button>
                                </div>

                                <!-- 订阅选项 -->
                                <div class="subscribe-options">
                                    <el-checkbox v-model="emailForm.weeklyDigest" class="option-item">
                                        接收每周精选文章汇总
                                    </el-checkbox>
                                    <el-checkbox v-model="emailForm.instantNotify" class="option-item">
                                        新文章发布时立即通知
                                    </el-checkbox>
                                </div>
                            </el-form>
                        </div>

                        <!-- 订阅状态显示 -->
                        <div v-if="emailSubscribeStatus" class="subscribe-status">
                            <el-alert :title="emailSubscribeStatus.title" :type="emailSubscribeStatus.type"
                                :description="emailSubscribeStatus.message" show-icon :closable="false" />
                        </div>
                    </div>

                    <!-- RSS订阅区域 -->
                    <div class="subscribe-section">
                        <div class="section-header">
                            <div class="section-icon">
                                <el-icon>
                                    <Connection />
                                </el-icon>
                            </div>
                            <h2 class="section-title">RSS订阅</h2>
                            <p class="section-description">
                                使用RSS阅读器订阅，获取完整的文章内容
                            </p>
                        </div>

                        <!-- RSS订阅源列表 -->
                        <div class="rss-sources">
                            <!-- 全部文章RSS -->
                            <div class="rss-item">
                                <div class="rss-info">
                                    <h3 class="rss-title">全部文章</h3>
                                    <p class="rss-description">订阅所有博客文章</p>
                                </div>
                                <div class="rss-actions">
                                    <el-button type="primary" size="small" @click="copyRssUrl(rssUrls.all)">
                                        <el-icon>
                                            <DocumentCopy />
                                        </el-icon>
                                        复制链接
                                    </el-button>
                                    <el-button type="success" size="small" @click="openRssReader(rssUrls.all)">
                                        <el-icon>
                                            <View />
                                        </el-icon>
                                        预览
                                    </el-button>
                                </div>
                            </div>

                            <!-- 技术文章RSS -->
                            <div class="rss-item">
                                <div class="rss-info">
                                    <h3 class="rss-title">技术文章</h3>
                                    <p class="rss-description">仅订阅技术相关文章</p>
                                </div>
                                <div class="rss-actions">
                                    <el-button type="primary" size="small" @click="copyRssUrl(rssUrls.tech)">
                                        <el-icon>
                                            <DocumentCopy />
                                        </el-icon>
                                        复制链接
                                    </el-button>
                                    <el-button type="success" size="small" @click="openRssReader(rssUrls.tech)">
                                        <el-icon>
                                            <View />
                                        </el-icon>
                                        预览
                                    </el-button>
                                </div>
                            </div>

                            <!-- 生活随笔RSS -->
                            <div class="rss-item">
                                <div class="rss-info">
                                    <h3 class="rss-title">生活随笔</h3>
                                    <p class="rss-description">订阅生活感悟和随笔文章</p>
                                </div>
                                <div class="rss-actions">
                                    <el-button type="primary" size="small" @click="copyRssUrl(rssUrls.life)">
                                        <el-icon>
                                            <DocumentCopy />
                                        </el-icon>
                                        复制链接
                                    </el-button>
                                    <el-button type="success" size="small" @click="openRssReader(rssUrls.life)">
                                        <el-icon>
                                            <View />
                                        </el-icon>
                                        预览
                                    </el-button>
                                </div>
                            </div>
                        </div>

                        <!-- RSS使用说明 -->
                        <div class="rss-guide">
                            <h3 class="guide-title">如何使用RSS订阅？</h3>
                            <div class="guide-steps">
                                <div class="guide-step">
                                    <div class="step-number">1</div>
                                    <div class="step-content">
                                        <h4>选择RSS阅读器</h4>
                                        <p>推荐使用 Feedly、Inoreader 或浏览器内置RSS功能</p>
                                    </div>
                                </div>
                                <div class="guide-step">
                                    <div class="step-number">2</div>
                                    <div class="step-content">
                                        <h4>添加订阅源</h4>
                                        <p>复制上面的RSS链接，粘贴到您的RSS阅读器中</p>
                                    </div>
                                </div>
                                <div class="guide-step">
                                    <div class="step-number">3</div>
                                    <div class="step-content">
                                        <h4>开始订阅</h4>
                                        <p>保存订阅源，即可开始接收最新文章更新</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 订阅统计区域 -->
                    <div class="subscribe-section">
                        <div class="section-header">
                            <div class="section-icon">
                                <el-icon>
                                    <DataAnalysis />
                                </el-icon>
                            </div>
                            <h2 class="section-title">订阅统计</h2>
                            <p class="section-description">
                                查看当前订阅情况和数据统计
                            </p>
                        </div>

                        <!-- 统计数据 -->
                        <div class="subscribe-stats">
                            <div class="stat-item">
                                <div class="stat-number">{{ subscribeStats.emailSubscribers }}</div>
                                <div class="stat-label">邮件订阅者</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-number">{{ subscribeStats.rssSubscribers }}</div>
                                <div class="stat-label">RSS订阅者</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-number">{{ subscribeStats.totalPosts }}</div>
                                <div class="stat-label">已发布文章</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-number">{{ subscribeStats.lastUpdate }}</div>
                                <div class="stat-label">最后更新</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <!-- 统一页脚组件 -->
        <AppFooter />
    </div>
</template>

<script setup lang="ts">
// ==================== 导入依赖 ====================

/**
 * Vue 3 组合式 API
 * @description 用于响应式数据管理和生命周期钩子
 */
import { ref, reactive, onMounted } from 'vue'

/**
 * Element Plus 组件和消息提示
 * @description 用于UI组件和用户反馈
 */
import { ElMessage, ElMessageBox } from 'element-plus'

/**
 * Element Plus 图标组件
 * @description 用于界面图标显示
 */
import {
    Message,
    Connection,
    DataAnalysis,
    DocumentCopy,
    View,
    User,
    Document
} from '@element-plus/icons-vue'

/**
 * 统一导航栏组件
 * @description 页面顶部导航栏
 */
import AppHeader from '../components/AppHeader.vue'

/**
 * 统一页脚组件
 * @description 页面底部页脚
 */
import AppFooter from '../components/AppFooter.vue'

// API工具导入
import { post, get, API_PATHS } from '../utils/api'

// ==================== 类型定义 ====================

// 邮件订阅请求数据接口
interface EmailSubscribeRequest {
    email: string
    weeklyDigest: boolean
    instantNotify: boolean
}

// 邮件订阅响应数据接口
interface EmailSubscribeData {
    success: boolean
    message: string
    data?: {
        subscriberId: number
        email: string
        subscriptionType: string
    }
}

// 订阅统计数据接口
interface SubscribeStatsData {
    emailSubscribers: number
    rssSubscribers: number
    totalPosts: number
    lastUpdate: string
}

// ==================== 响应式数据定义 ====================

/**
 * 邮件订阅表单数据
 * @description 存储邮件订阅的表单信息
 */
const emailForm = reactive({
    email: '',
    weeklyDigest: true,
    instantNotify: true
})

/**
 * 邮件订阅表单验证规则
 * @description 定义邮箱格式验证规则
 */
const emailRules = {
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ]
}

/**
 * 邮件订阅状态
 * @description 控制邮件订阅的加载状态
 */
const emailSubscribing = ref(false)

/**
 * 邮件订阅状态信息
 * @description 显示订阅成功或失败的状态信息
 */
const emailSubscribeStatus = ref<{
    title: string
    message: string
    type: 'success' | 'error' | 'warning' | 'info'
} | null>(null)

/**
 * 邮件订阅表单引用
 * @description 用于表单验证和提交
 */
const emailFormRef = ref()

/**
 * 是否使用示例数据
 * @description 标识当前是否使用示例数据
 */
const isUsingSampleData = ref(false)

/**
 * RSS订阅源URL配置
 * @description 定义不同分类的RSS订阅源地址
 */
const rssUrls = {
    all: `${window.location.origin}/rss/all.xml`,
    tech: `${window.location.origin}/rss/tech.xml`,
    life: `${window.location.origin}/rss/life.xml`
}

/**
 * 订阅统计数据
 * @description 显示订阅相关的统计数据
 */
const subscribeStats = reactive({
    emailSubscribers: 128,
    rssSubscribers: 256,
    totalPosts: 45,
    lastUpdate: '2024-01-15'
})

// ==================== 示例数据 ====================

// 示例订阅统计数据 - 当API调用失败时使用
const sampleSubscribeStats = {
    emailSubscribers: 156,
    rssSubscribers: 289,
    totalPosts: 52,
    lastUpdate: '2024-01-20'
}

// ==================== 方法定义 ====================

/**
 * 使用示例数据
 * @description 当API调用失败时，使用示例数据
 */
const useSampleData = () => {
    isUsingSampleData.value = true
    Object.assign(subscribeStats, sampleSubscribeStats)
}

/**
 * 处理邮件订阅
 * @description 验证邮箱格式并提交订阅请求
 */
const handleEmailSubscribe = async () => {
    try {
        // 验证表单
        const valid = await emailFormRef.value?.validate()
        if (!valid) return

        emailSubscribing.value = true

        // 准备订阅请求数据
        const subscribeData: EmailSubscribeRequest = {
            email: emailForm.email,
            weeklyDigest: emailForm.weeklyDigest,
            instantNotify: emailForm.instantNotify
        }

        // 调用后端邮件订阅API
        const response = await post<EmailSubscribeData>(API_PATHS.SUBSCRIBE.EMAIL, subscribeData)

        if (response && response.success) {
            // 订阅成功处理
            emailSubscribeStatus.value = {
                title: '订阅成功',
                message: `已成功订阅邮件通知，新文章发布时将发送到 ${emailForm.email}`,
                type: 'success'
            }

            // 清空表单
            emailForm.email = ''

            ElMessage.success('邮件订阅成功！')
        } else {
            // API返回错误
            emailSubscribeStatus.value = {
                title: '订阅失败',
                message: response?.message || '订阅过程中出现错误，请稍后重试',
                type: 'error'
            }
            ElMessage.error(response?.message || '邮件订阅失败，请重试')
        }

    } catch (error) {
        // 网络错误或API调用失败
        console.error('邮件订阅失败:', error)
        
        // 显示错误消息
        ElMessage.error('网络连接失败，请稍后重试')
        
        // 使用示例数据作为后备方案
        ElMessage.warning('后端服务暂时不可用，使用示例数据')
        useSampleData()
        
        // 模拟订阅成功
        emailSubscribeStatus.value = {
            title: '订阅成功（示例数据）',
            message: `已成功订阅邮件通知，新文章发布时将发送到 ${emailForm.email}`,
            type: 'success'
        }

        // 清空表单
        emailForm.email = ''

        ElMessage.success('邮件订阅成功（示例数据）！')
    } finally {
        emailSubscribing.value = false
    }
}

/**
 * 复制RSS链接到剪贴板
 * @description 将RSS订阅源链接复制到用户剪贴板
 * @param url - RSS订阅源URL
 */
const copyRssUrl = async (url: string) => {
    try {
        await navigator.clipboard.writeText(url)
        ElMessage.success('RSS链接已复制到剪贴板')
    } catch (error) {
        console.error('复制失败:', error)
        ElMessage.error('复制失败，请手动复制链接')
    }
}

/**
 * 在新窗口打开RSS阅读器
 * @description 在新标签页中打开RSS订阅源预览
 * @param url - RSS订阅源URL
 */
const openRssReader = (url: string) => {
    window.open(url, '_blank')
}

/**
 * 初始化页面数据
 * @description 页面加载时获取订阅统计数据
 */
const initPageData = async () => {
    try {
        // 调用后端API获取订阅统计数据
        const response = await get<SubscribeStatsData>(API_PATHS.SUBSCRIBE.STATS)
        
        if (response && response.success && response.data) {
            // 更新统计数据
            Object.assign(subscribeStats, response.data)
        } else {
            // API返回错误，使用示例数据
            console.warn('获取订阅统计数据失败，使用示例数据')
            useSampleData()
        }
    } catch (error) {
        // 网络错误或API调用失败
        console.error('获取订阅统计数据失败:', error)
        ElMessage.warning('后端服务暂时不可用，使用示例数据')
        useSampleData()
    }
}

// ==================== 生命周期钩子 ====================

/**
 * 组件挂载时初始化数据
 * @description 页面加载时获取必要的数据
 */
onMounted(() => {
    initPageData()
})
</script>

<style scoped lang="scss">
// 导入订阅页面样式
@use '../assets/styles/clients/_subscribe';
</style>
